package br.siagefi.mb;

import br.siagefi.model.Usuario;
import java.io.IOException;
import java.io.Serializable;
import javax.faces.bean.ManagedBean;
import javax.faces.bean.SessionScoped;
import javax.faces.context.ExternalContext;
import javax.faces.context.FacesContext;
import javax.servlet.RequestDispatcher;
import javax.servlet.ServletException;
import javax.servlet.ServletRequest;
import javax.servlet.ServletResponse;
import org.primefaces.event.ToggleEvent;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;


@ManagedBean
@SessionScoped
public class LoginBean implements Serializable {

    private Usuario usuario;
    
    private boolean toggleMenu;

    private transient final Logger LOG = LoggerFactory.getLogger(LoginBean.class);

    private String userName;
    private String password;

    /**
     * @return @throws IOException
     * @throws ServletException
     */
    public String doLogin() throws IOException, ServletException {
        LOG.debug("**** Executing doLogin method of LoginBean...");
        ExternalContext context = FacesContext.getCurrentInstance()
                .getExternalContext();

        RequestDispatcher dispatcher = ((ServletRequest) context.getRequest())
                .getRequestDispatcher("/j_spring_security_check?j_username=" + userName
                        + "&j_password=" + password);

        // Forwards to original destination or to error page
        dispatcher.forward((ServletRequest) context.getRequest(),
                (ServletResponse) context.getResponse());
        FacesContext.getCurrentInstance().responseComplete();

        //Usuario usuario = new Usuario();
//        usuario = us.buscar(userName);
        // It's OK to return null here because Faces is just going to exit.
        return null;
    }

    /**
     * @return
     */
    public String getUserName() {
        return this.userName;
    }

    /**
     * @param userName
     */
    public void setUserName(final String userName) {
        this.userName = userName;
    }

    /**
     * @return
     */
    public String getPassword() {
        return this.password;
    }

    /**
     * @param password
     */
    public void setPassword(final String password) {
        this.password = password;
    }

    public Usuario getUsuario() {
        return usuario;
    }

    public void setUsuario(Usuario usuario) {
        this.usuario = usuario;
    }

    public void switchToggle(ToggleEvent event) {
        if (event.getComponent().getId().equals("layoutMenu")) {
            toggleMenu = !toggleMenu;
        }
    }

    public boolean getToggleMenu() {
        return toggleMenu;
    }

}
